<script setup lang='ts'>
import { articleGetChannelAPI } from '@/apis/article';
import { EditArticleAPI, pbArticleAPI, UpdateArticleAPI } from '@/apis/publish';
import Ueditor from '@/components/Ueditor.vue';
import router from '@/router';
import type { channel_list } from '@/types/article';
import type { pbArticleParams } from '@/types/publish';
import { request } from '@/utils/request';
import { ArrowRight, Plus } from '@element-plus/icons-vue';
import { ElMessage, type FormInstance, type FormRules, type UploadFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import 'vue-ueditor-wrap';
const route = useRoute()
const params = ref<pbArticleParams>({
  title: '',
  channel_id: undefined,
  content: '',
  cover: {
    type: 1,
    images: []
  }
})


const onUpdate = async () => {
  const res = await EditArticleAPI(String(route.params.id))
  console.log(res.data);
  const { channel_id, content, cover, title, } = res.data
  params.value = {
    title,
    content,
    channel_id,
    cover,
  }
}
const channel = ref<channel_list[]>()
onMounted(async () => {
  const res = await articleGetChannelAPI()
  channel.value = res.data.channels
  if (route.params.id) {
    await onUpdate()
    filelist.value = params.value.cover.images.map(item => {
      return {
        url: item,
        name: item
      }
    })
  }
})
const filelist = ref<UploadUserFile[]>([])
const upload = async (options: UploadRequestOptions) => {
  const fd = new FormData()
  fd.append('image', options.file)
  const res = await request<{ url: string }>('/v1_0/upload', 'POST', fd)
  params.value.cover.images.push(res.data.url)
  formRef.value?.validateField('cover')
  return res.data.url
}
const onChangeType = () => {
  params.value.cover.images = []
  filelist.value = []
}
const onRemove = (uploadFile: UploadFile) => {
  params.value.cover.images = params.value.cover.images.filter(item => item !== uploadFile.response)
  formRef.value?.validateField('cover')
}
const formRules = ref<FormRules<pbArticleParams>>({
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  channel_id: [
    { required: true, message: '请选择文章频道', trigger: 'change' }
  ],
  cover: [{
    validator:(rule,value,callback)=>{ 
      if(value.type===1&&value.images.length<1){
          callback('请上传一张照片')
       }
       else if(value.type===3&&value.images.length<3){
        callback('请上传三张照片')
       }
       callback()
    },trigger:'change'},
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    {validator: (rule, value, callback)=>{
       if(value===`<p><br></p>`){
       callback('请输入文章内容')
       }else{
        callback()
       }
    }
}
  ]
})
const formRef = ref<FormInstance>()
const onPbArticle = async () => {
  formRef.value?.validate(async (val) => {
    if (val) {
      await pbArticleAPI(params.value)
      router.push('/article')
      ElMessage.success('发布成功')
    }
  })
}
const onUpdateArticle = async () => {
  formRef.value?.validate(async (val) => {
    if (val) {
      await UpdateArticleAPI(String(route.params.id), params.value)
      router.push('/article')
      ElMessage.success('修改成功')
    }
  })
}

const form = ref({
    noticeContent:''
})

const update=(value:any)=>{
  form.value.noticeContent = value
  params.value.content = form.value.noticeContent
}

</script>
<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>发布文章</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </template>
    <el-form label-width="100px" :model="params" :rules="formRules" ref="formRef">
      <el-form-item label="标题：" prop="title">
        <el-input size="large" style="width: 350px;" placeholder="请输入文章标题" v-model="params.title" />
      </el-form-item>
      <el-form-item label="频道：" prop="channel_id">
        <el-select placeholder="请选择" size="large" style="width: 240px" v-model="params.channel_id" clearable>
          <el-option v-for="item in channel" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="封面：" prop="cover">
        <el-radio-group v-model="params.cover.type" @change="onChangeType">
          <el-radio :value="-1">自动</el-radio>
          <el-radio :value="0">无图</el-radio>
          <el-radio :value="1">1张</el-radio>
          <el-radio :value="3">3张</el-radio>
        </el-radio-group>
        <el-upload v-show="params.cover.type > 0" list-type="picture-card" :limit="params.cover.type"
          :http-request="upload" v-model:file-list="filelist" @remove="onRemove">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="内容：" prop="content">
        <Ueditor v-model="form.noticeContent" @update:editorValue="update" :editorValue="form.noticeContent" ref="editorRef"></Ueditor>
      </el-form-item>
      <el-form-item>
        <el-button v-if="!$route.params.id" type="primary" @click="onPbArticle">发布文章</el-button>
        <el-button v-else type="primary" @click="onUpdateArticle">修改文章</el-button>
        <el-button type="primary" @click="">存入草稿</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style>
.el-form-item__content {
  display: block;
}

.ql-blank {
  height: 200px;
}
</style>